//存储消息到浏览器
function saveMessage(userid, fromid, message) {
    var db = openDatabase('testDB', '1.0', 'Test DB', 20 * 1024 * 1024);
    db.transaction(function (context) {
        context.executeSql('CREATE TABLE IF NOT EXISTS MessageTable(id unique,UserId,FromId,Message)');

        context.executeSql('SELECT * FROM MessageTable where UserId=? and FromId=?', [userid, fromid], function (context, results) {
            var len = results.rows.length, i;
            console.log('Got ' + len + ' rows.');
            for (i = 0; i < len; i++) {
                console.log('id: ' + results.rows.item(i).id);
                console.log('Message: ' + results.rows.item(i).Message);
            }
            if (len == 0) {
                //插入数据

                context.executeSql('INSERT INTO MessageTable (UserId,FromId,Message) VALUES (?,?,?)', [userid, fromid, message]);
            } else {
                var item = results.rows.item(0).Message;
                if (item == null) {
                    item = "";
                }

                item += message;
                // UPDATE user SET loginId = #{loginId} WHERE  id =#{id}

                context.executeSql('update MessageTable set Message= ? Where UserId=? and FromId=?', [item, userid, fromid]);
            }


        });
        // if (!window.localStorage) {
        //     alert("浏览器支持localstorage");
        // } else {
        //     var storage = window.localStorage;
        //
        //     var item = storage.getItem(userid+"from"+fromid);
        //     if (item == null) {
        //         item = "";
        //     }
        //
        //     var html = obj.fromUser.name + ": " + obj.data.test;
        //     item += '<div class="left">' + html + '</div> <br/>';
        //     storage.setItem(userid, item);
        // }
    });
}

function findOldMessage(userid, fromid) {
    var db = openDatabase('testDB', '1.0', 'Test DB', 20 * 1024 * 1024);

    db.transaction(function (context) {
        context.executeSql('CREATE TABLE IF NOT EXISTS MessageTable(id unique,UserId,FromId,Message,Useful)');


        context.executeSql('SELECT * FROM MessageTable where UserId=? and FromId=?'
            , [userid, fromid]
            , function (context, results) {
                var len = results.rows.length, i;
                console.log('findOldMessage Got ' + len + ' rows.');
                for (i = 0; i < len; i++) {
                    console.log('id: ' + results.rows.item(i).id);
                    console.log('Message: ' + results.rows.item(i).Message);
                }
                var item;
                if (len != 0) {
                    item = results.rows.item(0).Message;
                    if (item == null) {
                        item = "";
                    }
                }

                showOldMessage(item);

            });

    });

}